package com.hzhq.contract.demo;

import com.hzhq.contract.util.MyBeanUtils;
import lombok.Data;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;
/**
 * @author hzhq
 * @create 2021/4/9 3:07 下午
 * @email hzhq1255@163.com
 *
 * 用
 */
public class TestBeanAttribute {


    @Data
    private static class Person{
        private String name;
        private String pwd;
        private Integer age;


    }

    @Data
    private static class SubPerson {

        private String name;
        private String pwd;
        private Integer age;
        private String address;
    }

    public static void reflect(Person e) throws Exception{
        Class cls = e.getClass();
        Field[] fields = cls.getDeclaredFields();
        for(int i=0; i<fields.length; i++){
            Field f = fields[i];
            f.setAccessible(true);
            System.out.println("属性名:" + f.getName() + " 属性值:" + f.get(e));
        }
    }

    public static <T> T dynamicCopySameBean(T source, T target) {
        if (! source.getClass().isInstance(target)){
            return null;
        }
        try {
            for (Field field: source.getClass().getDeclaredFields()){
                field.setAccessible(true);
                if (null == field.get(source)){
                    continue;
                }
                String key = field.getName();
                System.out.println(key);
                String getMethodName = "get" + key.substring(0,1).toUpperCase()+key.substring(1);
                String setMethodName = "set" + key.substring(0,1).toUpperCase()+key.substring(1);
                Method getMethod = source.getClass().getDeclaredMethod(getMethodName);
                T value = (T) getMethod.invoke(source);
                target.getClass().getMethod(setMethodName,value.getClass()).invoke(target,value);
            }
            return target;
        }catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e){
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) throws Exception {
        Person person = new Person();
        person.setName("zhangsan");
        person.setPwd("123");
        person.setAge(21);
        Person person1 = new Person();
        person1.setName("lisi");
        person1.setAge(22);

//        Person person2 = (Person) dynamicCopySameBean(new Object(),person);
//        System.out.println(person);
//        System.out.println(person2);

        SubPerson subPerson = new SubPerson();
        BeanUtils.copyProperties(person,subPerson);
        //BeanUtils.copyProperties(person1,person);
        //MyBeanUtils.dynamicCopySameBean(person1,person);
        System.out.println(subPerson);
        System.out.println(person);
    }
}
